const express = require('express');
const router = express.Router();
const rolePermissionService = require('../../services/rolePermissionService');
const adminAuth = require('../../middleware/adminAuth');
const { checkPermission } = require('../../middleware/permission');

/**
 * 获取角色列表
 */
router.get('/', adminAuth, checkPermission('role', 'read'), async (req, res) => {
  try {
    const {
      page = 1,
      limit = 20,
      search,
      status,
      includePermissions = false
    } = req.query;

    const result = await rolePermissionService.getRoleList({
      page: parseInt(page),
      limit: parseInt(limit),
      search,
      status,
      includePermissions: includePermissions === 'true'
    });

    res.json({
      success: true,
      data: result
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      message: '获取角色列表失败',
      error: error.message
    });
  }
});

/**
 * 获取所有角色（不分页，用于下拉选择）
 */
router.get('/all', adminAuth, async (req, res) => {
  try {
    const result = await rolePermissionService.getRoleList({
      page: 1,
      limit: 1000,
      status: 'active'
    });

    res.json({
      success: true,
      data: result.roles
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      message: '获取角色列表失败',
      error: error.message
    });
  }
});

/**
 * 获取角色详情
 */
router.get('/:id', adminAuth, checkPermission('role', 'read'), async (req, res) => {
  try {
    const roleId = parseInt(req.params.id);
    const role = await rolePermissionService.getRoleById(roleId);

    res.json({
      success: true,
      data: role
    });
  } catch (error) {
    res.status(404).json({
      success: false,
      message: error.message
    });
  }
});

/**
 * 创建角色
 */
router.post('/', adminAuth, checkPermission('role', 'create'), async (req, res) => {
  try {
    const { name, displayName, description, level, permissionIds } = req.body;

    if (!name || !displayName) {
      return res.status(400).json({
        success: false,
        message: '角色名称和显示名称不能为空'
      });
    }

    const role = await rolePermissionService.createRole({
      name,
      displayName,
      description,
      level,
      permissionIds
    }, req.adminId);

    res.status(201).json({
      success: true,
      message: '角色创建成功',
      data: role
    });
  } catch (error) {
    res.status(400).json({
      success: false,
      message: error.message
    });
  }
});

/**
 * 更新角色
 */
router.put('/:id', adminAuth, checkPermission('role', 'update'), async (req, res) => {
  try {
    const roleId = parseInt(req.params.id);
    const { name, displayName, description, level, status, permissionIds } = req.body;

    await rolePermissionService.updateRole(roleId, {
      name,
      displayName,
      description,
      level,
      status,
      permissionIds
    }, req.adminId);

    res.json({
      success: true,
      message: '角色更新成功'
    });
  } catch (error) {
    res.status(400).json({
      success: false,
      message: error.message
    });
  }
});

/**
 * 删除角色
 */
router.delete('/:id', adminAuth, checkPermission('role', 'delete'), async (req, res) => {
  try {
    const roleId = parseInt(req.params.id);
    
    await rolePermissionService.deleteRole(roleId);

    res.json({
      success: true,
      message: '角色删除成功'
    });
  } catch (error) {
    res.status(400).json({
      success: false,
      message: error.message
    });
  }
});

module.exports = router;